<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 竞赛数据
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-lx-add"
                    class="handle-del mr10"
                    @click="handleAdd"
                >添加</el-button>
                <el-input v-model="query.contestName" placeholder="比赛名称" class="handle-input mr10"></el-input>
                <!-- <el-input v-model="query.startTime" placeholder="开始时间" class="handle-input mr10"></el-input>
                <el-input v-model="query.endTime" placeholder="结束时间" class="handle-input mr10"></el-input> -->
                <el-select v-model="query.status" slot="prepend" clearable placeholder="状态" class="handle-input mr10">
                    <el-option label="有效" value="0"></el-option>
                    <el-option label="无效" value="1"></el-option>
                </el-select>
                <el-button type="primary" style="margin-right: 5px;" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <download-excel
                    class="export-excel-wrapper"
                    :data="selectData"
                    :fields="json_fields"
                    :header="title"
                    name="竞赛数据.xls"
                    >
                    <el-button type="primary" icon="el-icon-lx-down" @click="handleExport">导出选中</el-button>
                </download-excel>
                <download-excel
                    class="export-excel-wrapper"
                    :data="allData"
                    :fields="json_fields"
                    :header="title"
                    name="竞赛数据(全部).xls"
                    >
                    <el-button type="primary" icon="el-icon-lx-down" style="margin-left: 3%;" @click="handleExportAll">全部导出</el-button>
                </download-excel>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="contestName" label="比赛名称"></el-table-column>
                <el-table-column prop="startTime" label="开始时间"></el-table-column>
                <el-table-column prop="endTime" label="结束时间"></el-table-column>
                <el-table-column prop="answerTimes" label="单人可答题次数"></el-table-column>
                <el-table-column prop="time" label="限时（单位s）"></el-table-column>
                <el-table-column label="题型">
                    <template slot-scope="scope">
                        <p :key="item" v-for = "item in scope.row.questionNum">{{item.type}} : {{ item.count }}</p>
                    </template>
                </el-table-column>
                <el-table-column label="题目列表">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-info"
                            @click="handleShow(scope.$index, scope.row)"
                        >查看</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">{{scope.row.status==0 ? '有效':(scope.row.status==1 ? '无效':'无')}}</template>
                </el-table-column>

                <!-- <el-table-column prop="createTime" label="创建时间"></el-table-column>
                <el-table-column prop="updateTime" label="更新时间"></el-table-column> -->
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.current"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="比赛名称">
                    <el-input v-model="form.contestName"></el-input>
                </el-form-item>
                <el-form-item label="开始时间">
                    <el-date-picker
                        v-model="form.startTime"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="timestamp"
                        placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker
                        v-model="form.endTime"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="timestamp"
                        placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="单人可答题次数">
                    <el-input v-model="form.answerTimes"></el-input>
                </el-form-item>
                <el-form-item label="限时(s)">
                    <el-input v-model="form.time"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="form.status" clearable placeholder="请选择" class="formSelect">
                        <el-option label="有效" value = "0"></el-option>
                        <el-option label="无效" value = "1"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="各个题目类型的数量">
                    <el-input v-model="form.questionNum"></el-input>
                </el-form-item> -->
                <el-form-item label="题目列表">
                    <!-- <el-input v-model="addform.questionList"></el-input> -->
                    <el-button @click="goAdd(1)">去选择</el-button>
                    <el-collapse v-model="activeName" accordion>
                        <el-collapse-item title="题目列表" name="1">
                            <div v-for="(item,index) in edit_question">{{item.content}}</div>
                            <!-- <div>在界面中一致：所有的元素和结构需保持一致，比如：设计样式、图标和文本、元素的位置等。</div> -->
                        </el-collapse-item>
                    </el-collapse>
                </el-form-item>
                
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="题目列表" :visible.sync="dialogTableVisible">
            <el-table :data="gridData">
                <el-table-column prop="content" label="题干"></el-table-column>
                <el-table-column prop="score" sortable label="分值"></el-table-column>
                <el-table-column prop="questionType" label="题型"></el-table-column>
                
                <el-table-column label="选项"  width="200">
                    <template slot-scope="scope">
                        <p :key="item" v-for = "item in scope.row.selection">{{item.select}} : {{ item.selectContent }}</p>
                    </template>
                </el-table-column>
                <el-table-column prop="answer" label="答案">
                    <template slot-scope="scope">
                        <el-tag type="success">{{scope.row.answer}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="analysis" label="解析"></el-table-column>
                <el-table-column prop="remark" label="备注"></el-table-column>
                <el-table-column prop="type" label="类型"></el-table-column>
                <el-table-column label="难度">
                    <template slot-scope="scope">{{scope.row.difficulty==0 ? '简单':(scope.row.difficulty==1 ? '中等':(scope.row.difficulty==2 ? '困难':'未知'))}}</template>
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">{{scope.row.status==0 ? '有效':(scope.row.status==1 ? '无效':'无')}}</template>
                </el-table-column>
                <el-table-column label="正确率">
                    <template slot-scope="scope">{{scope.row.writeCnt == 0 ? 0 : (scope.row.correctCnt/scope.row.writeCnt).toFixed(3)}}</template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 添加弹出框 -->
        <el-dialog title="添加竞赛" :visible.sync="addVisible" width="30%">
            <el-form ref="addform" :model="addform" label-width="70px">
                <el-form-item label="比赛名称">
                    <el-input v-model="addform.contestName"></el-input>
                </el-form-item>
                <el-form-item label="开始时间">
                    <el-date-picker
                        v-model="addform.startTime"
                        type="datetime"
                        value-format="timestamp"
                        placeholder="选择开始时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker
                        v-model="addform.endTime"
                        type="datetime"
                        value-format="timestamp"
                        placeholder="选择结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="单人可答题次数">
                    <el-input v-model="addform.answerTimes"></el-input>
                </el-form-item>
                <el-form-item label="限时(s)">
                    <el-input v-model="addform.time"></el-input>
                </el-form-item>
                <!-- <el-form-item label="各个题目类型的数量">
                    <el-input v-model="addform.questionNum"></el-input>
                </el-form-item> -->
                <el-form-item label="题目列表">
                    <!-- <el-input v-model="addform.questionList"></el-input> -->
                    <el-button @click="goAdd(0)">去选择</el-button>
                    <el-collapse v-model="activeName" accordion>
                        <el-collapse-item title="题目列表" name="1">
                            <div v-for="(item,index) in select_question">{{item.content}}</div>
                            <!-- <div>在界面中一致：所有的元素和结构需保持一致，比如：设计样式、图标和文本、元素的位置等。</div> -->
                        </el-collapse-item>
                    </el-collapse>
                </el-form-item>
                <!-- <el-form-item label="状态">
                    <el-select v-model="addform.status" clearable placeholder="请选择" class="formSelect">
                        <el-option label="有效" value = "0"></el-option>
                        <el-option label="无效" value = "1"></el-option>
                    </el-select>
                </el-form-item> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
                
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getContestList, deleteContest, addContest, updateContest,getQuestionByIds,getAllContestList } from '../../api/index';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                current: 1,
                pageSize: 10,
            },
            tableData: [],
            selectData:[],
            allData:[],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            addVisible: false,
            activeName:'1',
            dialogTableVisible:false,
            gridData:[],
            pageTotal: 0,
            form: {
                'contestName': '',
                'startTime':'',
                'endTime':'',
                'answerTimes':'',
                'time':'',
                'questionList': '',
                'status':''
            },
            idx: -1,
            id: -1,
            title:'竞赛数据',
            select_question:{},//从题目列表中选择的题目数据
            edit_question:{},
            json_fields: {
                'id': 'id',
                '比赛名称': 'contestName',
                '开始时间': 'startTime',
                '结束时间': 'endTime',
                '单人可答题次数': 'answerTimes',
                '限时（单位s）': 'time',
                '各个题目类型的数量': 'questionNum',
                '题目列表': 'questionList',
                '状态': 'status',
                '创建时间': 'createTime',
                '更新时间': 'updateTime'
            },
            addform: {
                'contestName': '',
                'startTime':'',
                'endTime':'',
                'answerTimes':'',
                'time':'',
                'questionList': '',
            }
        };
    },
    created() {
        this.getData();
        getAllContestList().then(res => {
            this.allData = res.data
            console.log(this.allData)
            // let tmp=this.allData
            const tmp = this.deepClone(this.allData)
            console.log(tmp)
            for(var i=0;i<tmp.length;i++){
                var temp=''
                var temp1=''
                tmp[i].status=tmp[i].status == 1 ? '无效' : '有效'
                if(tmp[i].questionNum!=null){
                    for(var j=0;j<tmp[i].questionNum.length;++j){
                        temp = temp+tmp[i].questionNum[j].type + ':' + tmp[i].questionNum[j].count
                        temp1 = temp1 + ',' + tmp[i].questionNum[j].answerList.join(',')
                    }
                }
                
                tmp[i].questionNum = temp
                tmp[i].questionList = temp1
            }
            console.log(tmp)
            this.allData=tmp
        })
    },
    watch:{
        $route:{
            handler(val,oldval){
                if(val.path=="/contest"){
                    if(this.$route.query.selection!=undefined && this.$route.query.selection!=null){
                        let id=this.$route.query.id
                        console.log(id)
                        if(id==0){
                            this.select_question = this.$route.query.selection
                            this.addVisible=true
                        }else{
                            this.edit_question = this.$route.query.selection
                            console.log(this.edit_question)
                            this.$forceUpdate()
                            this.editVisible = true;
                        }
                    }
                }
            },
            // 深度观察监听
            deep: true
        }
    },
    methods: {
        getData() {
            getContestList(this.query).then(response => {
                if(response.code != 0){
                    this.$message.error(response.message)
                }else{
                    let res = response.data
                    this.tableData = res.records;
                    this.pageTotal = res.total;
                }
            });
        },
        deepClone(target) {
            if (typeof target === 'object' && target !== null) {
                return JSON.parse(JSON.stringify(target));
            } else {
                return target;
            }
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'current', 1);
            this.getData();
        },

        goAdd(id){
            if(id==0){
               this.$router.push({path:'/add_question',query:{selection:this.select_question,id:0}})
               this.addVisible=false
            }else{
                this.$router.push({path:'/add_question',query:{selection:this.edit_question,id:1}})
                this.editVisible=false
            }
        },     
        handleShow(index,row){
            console.log(row)
            let arr = row.questionNum
            let param = {
                ids:[],
                current:1,
                pageSize:10
            }
            for(var i=0;i<arr.length;++i){
                for(var j = 0;j<arr[i].answerList.length;++j){
                    param.ids.push(arr[i].answerList[j])
                }
            }
            console.log(param)
            getQuestionByIds(param).then(res => {
                console.log(res)
                if(res.code != 0){
                    this.$message.error(res.message)
                    this.dialogTableVisible = true
                }else{
                    this.gridData=res.data.records
                }
            })
            this.dialogTableVisible = true
            console.log(row)
        },
        //导出表格
        handleExport() {
            if(this.multipleSelection.length==0){
                this.$message.error('请选中要导出的竞赛数据！')
            }else{
                this.$message.success('导出成功！')
            }
        },
        handleExportAll(){
            this.$message.success('导出成功！')
        },
        //添加竞赛
        saveAdd() {
            let arr=[]
            let temp={}
            for(var i=0;i<this.select_question.length;++i){
                temp={
                    id:'',
                    questionType:''
                }
                temp.id=this.select_question[i].id
                temp.questionType=this.select_question[i].questionType
                arr.push(temp)
            }
            this.addform.questionList=arr
            console.log(this.addform)
            addContest(this.addform).then(response => {
                let res = response.data
                console.log(res)
                if(res.code!=0){
                    this.$message.error(res.message)
                }else{
                    this.$message.success('添加成功!')
                    this.addVisible=false
                    this.getData()
                }
                
            }).catch(err => {
                this.$message.error('添加失败，请检查信息是否正确!')
            })
        },
        handleAdd() {
            this.addVisible=true
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    deleteContest(row).then( res => {
                        if(res.code!=0){
                            this.$message.error(res.message)
                        }else{
                            this.$message.success('删除成功');
                            this.tableData.splice(index, 1);
                            this.pageTotal-=1
                        }
                    }).then(()=>{
                        
                    }).catch(err => {
                        this.$message.error('删除失败！')
                    })
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            const tmp = this.deepClone(val)
            console.log(tmp)
            for(var i=0;i<tmp.length;i++){
                var temp=''
                var temp1=''
                tmp[i].status=tmp[i].status == 1 ? '无效' : '有效'
                if(temp[i].questionNum!=null){
                    for(var j=0;j<tmp[i].questionNum.length;++j){
                        temp = temp+tmp[i].questionNum[j].type + ':' + tmp[i].questionNum[j].count
                        temp1 = temp1 + ',' + tmp[i].questionNum[j].answerList.join(',')
                    }
                }
                
                tmp[i].questionNum = temp
                tmp[i].questionList = temp1
            }
            console.log(tmp)
            this.selectData=tmp
            console.log(this.selectData)
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            let arr = row.questionNum
            let param = {
                ids:[],
                current:1,
                pageSize:999//要查询全部题目，不能设置限制
            }
            for(var i=0;i<arr.length;++i){
                for(var j = 0;j<arr[i].answerList.length;++j){
                    param.ids.push(arr[i].answerList[j])
                }
            }
            getQuestionByIds(param).then(res => {
                if(res.code != 0){
                    this.$message.error(res.message)
                }else{
                    this.edit_question=res.data.records
                    this.idx = index;
                    this.form = row;
                    this.form.status=this.form.status+''
                    console.log(this.edit_question)
                    this.editVisible = true;
                }
            })
            
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;

            let arr=[]
            let temp={}
            for(var i=0;i<this.edit_question.length;++i){
                temp={
                    id:'',
                    questionType:''
                }
                temp.id=this.edit_question[i].id
                temp.questionType=this.edit_question[i].questionType
                arr.push(temp)
            }
            this.form.questionList=arr

            updateContest(this.form).then(res => {
                if(res.code!=0){
                    this.$message.error(res.message)
                    this.getData()
                }else{
                    this.$message.success(`修改第 ${this.idx + 1} 行成功!`);
                    this.$set(this.tableData, this.idx, this.form);
                    this.$forceUpdate()
                }
                
            }).catch(err => {
                this.$message.error('修改第 ${this.idx + 1} 行失败!')
            })
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'current', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
    display: flex;
}

.handle-select {
    width: 120px;
}

.formSelect {
    width: 100%;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
